package com.library.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.MemoryCacheImageInputStream;
import java.io.*;
import java.util.Iterator;

@Slf4j
public class FileUtil {

    /**
     * 校验文件是否为图片类型
     * @param mapObj
     * @return
     */
    public static boolean validateImageType(byte[] mapObj)
    {
        boolean ret =false;
        ByteArrayInputStream bais = null;
        MemoryCacheImageInputStream mcis = null;
        try
        {
            bais = new ByteArrayInputStream(mapObj);
            mcis = new MemoryCacheImageInputStream(bais);
            Iterator<ImageReader> itr = ImageIO.getImageReaders(mcis);
            while(itr.hasNext())
            {
                ImageReader reader = (ImageReader)itr.next();
                String imageName = reader.getClass().getSimpleName();
                if(imageName!=null &&("GIFImageReader".equals(imageName)
                        ||"JPEGImageReader".equals(imageName)
                        ||"PNGImageReader".equals(imageName)
                        ||"BMPImageReader".equals(imageName)))
                {
                    ret =true;
                }
            }
        }
        finally
        {
            //关闭流
        }
        return ret;
    }

    /**
     * 获取文件字节流
     * @param path
     * @return
     * @throws IOException
     */
    public static byte[] getBytes(String path) throws IOException {
        if(StringUtils.isEmpty(path)){
            return null;
        }
        File f = new File(path);
        if (!f.exists()) {
            return null;
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len = 0;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("获取文件字节流失败",e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
        return null;
    }
}
